package com.xhc.ui;

import com.xhc.util.ExcelProcessor;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

public class QRGeneratorUI {
    private JFrame frame;
    private JTextField inputPathField;
    private JTextField outputPathField;
    private JTextField sheetNameField;
    private JTextField columnField;
    private JTextField startRowField;
    private JTextField endRowField;

    public static void launchUI() {
        // 设置Windows风格的外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> new QRGeneratorUI().initialize());
    }

    private void initialize() {
        createMainWindow();
        createUIComponents();
        frame.setVisible(true);
    }

    private void createMainWindow() {
        frame = new JFrame("宁波新华昌Excel数据转二维码工具");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(700, 600);  // 增大窗口尺寸以容纳提示信息
        frame.setLocationRelativeTo(null);

        // 设置窗口图标（任务栏显示的小图标）
        try {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/logo.jpg"));
            Image image = icon.getImage().getScaledInstance(64, 64, Image.SCALE_SMOOTH);
            frame.setIconImage(image);
        } catch (Exception e) {
            System.out.println("未找到logo图片");
        }
    }

    private void createUIComponents() {
        JPanel mainPanel = new JPanel(new BorderLayout(8, 8));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));

        // 创建顶部面板（包含大logo和标题）
        JPanel headerPanel = new JPanel(new BorderLayout(20, 0));
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 15, 0));

        // 加载并显示大logo
        try {
            ImageIcon originalIcon = new ImageIcon(getClass().getResource("/images/logo.jpg"));
            Image originalImage = originalIcon.getImage();
            // 设置logo显示尺寸为150x150
            Image scaledImage = originalImage.getScaledInstance(150, 150, Image.SCALE_SMOOTH);
            JLabel logoLabel = new JLabel(new ImageIcon(scaledImage));
            logoLabel.setHorizontalAlignment(SwingConstants.CENTER);
            headerPanel.add(logoLabel, BorderLayout.WEST);
        } catch (Exception e) {
            System.out.println("未找到logo图片");
            // 如果找不到图片，显示文字替代
            headerPanel.add(new JLabel("[LOGO]"), BorderLayout.WEST);
        }

        // 标题
        JLabel titleLabel = new JLabel("宁波新华昌Excel数据转二维码工具");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
        headerPanel.add(titleLabel, BorderLayout.CENTER);

        mainPanel.add(headerPanel, BorderLayout.NORTH);

        // 表单部分 - 改为使用GridBagLayout以获得更好的控制
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 输入文件路径字段
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0;
        formPanel.add(new JLabel("请输入Excel文件路径："), gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        inputPathField = new JTextField();
        inputPathField.setPreferredSize(new Dimension(300, 30));
        formPanel.add(inputPathField, gbc);

        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.weightx = 0;
        JButton browseInputBtn = new JButton("选择文件");
        browseInputBtn.setPreferredSize(new Dimension(100, 30));
        browseInputBtn.addActionListener(e -> browseInputFile(inputPathField));
        formPanel.add(browseInputBtn, gbc);

        mainPanel.add(formPanel, BorderLayout.CENTER);

        // 添加自定义提示信息面板（在表单和按钮之间）
        JPanel infoPanel = createInfoPanel();
        mainPanel.add(infoPanel, BorderLayout.SOUTH);

        frame.add(mainPanel);
    }

    private JPanel createInfoPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));

        // 创建提示信息文本区域
        JTextArea infoTextArea = new JTextArea();
        infoTextArea.setEditable(false);
        infoTextArea.setLineWrap(true);
        infoTextArea.setWrapStyleWord(true);
        infoTextArea.setBackground(UIManager.getColor("Panel.background"));
        infoTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        infoTextArea.setText("【使用说明】\n" +
                "• 请确保Excel文件格式正确，数据表名必须为'Sheet1'\n" +
                "• 签订单：必须在A列\n" +
                "• 计划日期：必须在B列（格式：2099/08/20）\n" +
                "• 起始箱号必须C在列,结束箱号必须在D列\n" +
                "• 箱型：必须在E列（例如：40HC、20DV）\n" +
                "• 从第二行开始转换\n" +
                "• 转换后的文件将保存在原文件同目录下，文件名：“ 日期+源文件名+含二维码+后缀 ”\n" +
                "• 转换过程中请勿关闭程序，转换完成后会提示成功信息");

        // 创建转换按钮
        JButton convertBtn = new JButton("转 换");
        convertBtn.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        convertBtn.setPreferredSize(new Dimension(220, 45));
        convertBtn.addActionListener(e -> convertToQR());

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(convertBtn);

        // 将提示信息和按钮添加到面板
        panel.add(infoTextArea, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private void addFormField(JPanel panel, String label, JTextField textField) {
        panel.add(new JLabel(label));
        panel.add(textField);
    }

    private void addFormField(JPanel panel, String label, JTextField textField,
                              String buttonText, java.awt.event.ActionListener listener) {
        panel.add(new JLabel(label));

        JPanel fieldPanel = new JPanel(new BorderLayout());
        fieldPanel.add(textField, BorderLayout.CENTER);

        JButton button = new JButton(buttonText);
        button.addActionListener(listener);
        fieldPanel.add(button, BorderLayout.EAST);

        panel.add(fieldPanel);
    }

    private void browseInputFile(JTextField textField) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择Excel文件");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.addChoosableFileFilter(
                new FileNameExtensionFilter("Excel文件 (*.xlsx, *.xls)", "xlsx", "xls")
        );

        if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
            textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }

    private void browseOutputFolder(JTextField textField) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择输出文件夹");
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
            textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }

    private void convertToQR() {
        try {
            ConversionParams params = validateAndGetParams();
            String outputFilePath = generateOutputFilePath(params);

            ExcelProcessor.processExcelToQR(
                    params.inputPath,
                    outputFilePath,
                    "Sheet1",
                    "A",
                    "B",
                    "C",
                    "D",
                    "E"
            );

            showSuccess("转换成功！文件已保存到: " + outputFilePath);
        } catch (ValidationException e) {
            showError(e.getMessage());
        } catch (Exception e) {
            showError("转换失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private ConversionParams validateAndGetParams() throws ValidationException {
        ConversionParams params = new ConversionParams();

        // 验证输入文件
        params.inputPath = inputPathField.getText().trim();
        if (params.inputPath.isEmpty()) {
            throw new ValidationException("请选择要转换的Excel文件");
        }

        File inputFile = new File(params.inputPath);
        if (!inputFile.exists()) {
            throw new ValidationException("输入的Excel文件不存在: " + params.inputPath);
        }

        if (!params.inputPath.toLowerCase().matches(".*\\.xlsx?$")) {
            throw new ValidationException("请选择有效的Excel文件 (.xlsx 或 .xls)");
        }

        return params;
    }

    private String generateOutputFilePath(ConversionParams params) {
        File inputFile = new File(params.inputPath);
        params.outputPath = inputFile.getParent();
        String inputFileName = inputFile.getName().replaceFirst("[.][^.]+$", "");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return params.outputPath + File.separator + LocalDate.now().format(formatter)+inputFileName +"含二维码.xlsx";
    }

    private void showError(String message) {
        JOptionPane.showMessageDialog(frame, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    private void showSuccess(String message) {
        JOptionPane.showMessageDialog(frame, message, "成功", JOptionPane.INFORMATION_MESSAGE);
    }

    private static class ConversionParams {
        String inputPath;
        String outputPath;
    }

    private static class ValidationException extends Exception {
        public ValidationException(String message) {
            super(message);
        }
    }
}